<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- 搜索与添加区域 -->
        <el-row :gutter="20">
          <el-col :span="2">
            <el-button type="primary">添加</el-button>
          </el-col>
          <el-col :span="8"></el-col>
        </el-row>
      </div>

      <el-table :data="rolesList" :stripe="true">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="{row}">
            <el-row
              :class="['vcenter', 'row-bottom', i1 === 0 ?  'row-top' : ''] "
              v-for="(item1, i1) in row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5" v-if="item1.ruleName">
                <el-tag
                  type
                  :closable="true"
                  @close="deleteRuleById(row, item2.id)"
                >{{item1.ruleName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <!-- 循环二级权限 -->
                <el-row
                  :class="['vcenter', i2 === 0 ?  '' : 'row-top']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      :closable="true"
                      @close="deleteRuleById(row, item2.id)"
                    >{{item2.ruleName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      :closable="true"
                      @close="deleteRuleById(row, item3.id)"
                    >{{item3.ruleName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="{row}">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showRuleDialogForm(row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog title="权限分配" :visible.sync="ruleDialogFormVisible" @close="ruleDialogFormClose">
      <el-tree
        :data="rulesList"
        :props="rulesProps"
        :show-checkbox="true"
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="roleRulesArray"
        ref="treeRef"
      ></el-tree>

      <div slot="footer" class="dialog-footer">
        <el-button @click="ruleDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRoleAllRules">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      rolesList: [],
      // 控制分配权限对话框显示与隐藏
      ruleDialogFormVisible: false,
      // 权限表单
      ruleForm: {},
      // 所有权限数据
      rulesList: [],
      // 树形控件的属性绑定对象
      rulesProps: {
        label: 'name',
        children: 'children'
      },
      // 角色已有的权限id数组
      roleRulesArray: [],
      // 即将分配权限的角色id
      roleId: ''
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取所有角色列表
    async getRoleList() {
      await this.$http
        .get('roles')
        .then(res => {
          res = res.data
          if (!res.code || res.code == 0)
            return this.$message.error(res.msg || '获取数据失败')
          this.rolesList = res.data
        })
        .catch(err => {
          return this.$message.error(err.message)
        })
    },
    // 根据id删除角色权限
    async deleteRuleById(role, ruleId) {
      const confRes = await this.$confirm('确认删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confRes !== 'confirm') {
        return this.$message.info('操作取消')
      }

      await this.$http
        .delete(`/roles/${role.id}/rules/${ruleId}`)
        .then(res => {
          res = res.data
          if (!res.code || res.code == 0)
            return this.$message.error(res.msg || '操作失败')

          // this.getRoleList()
          role.children = res.data
        })
        .catch(err => {
          return this.$message.error(err.message || '操作失败')
        })
    },
    // 展示分配权限对话框
    async showRuleDialogForm(role) {
      this.roleId = role.id
      // 获取所有权限数据
      await this.$http
        .get('/rules/tree')
        .then(res => {
          res = res.data
          // console.log(res)
          this.rulesList = res.data

          // 获取指定角色的id
          this.getRoleRulesIds(role, this.roleRulesArray)

          this.ruleDialogFormVisible = true
        })
        .catch(err => {
          return this.$message.error(err.message || '获取失败')
        })
    },
    // 通过递归的形式获取角色所有三级权限的id,并存储到数组中
    getRoleRulesIds(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(element => {
        this.getRoleRulesIds(element, arr)
      })
    },
    // 监听分配权限窗口关闭，清空 roleRulesArray
    ruleDialogFormClose() {
      this.roleRulesArray = []
    },
    // 更新指定角色所有权限规则
    async updateRoleAllRules() {
      const rulesKeys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(rulesKeys)

      const rulesKeysStr = rulesKeys.join(',')
      await this.$http
        .post(`/roles/${this.roleId}/rules`, { rulesIds: rulesKeysStr })
        .then(res => {
          res = res.data
          if (!res.code || res.code == 0)
            return this.$message.error(res.msg || '操作失败')

          this.$message.success(res.msg || '操作成功')
          this.getRoleList()
          this.ruleDialogFormVisible = false

        })
        .catch(err => {
          return this.$message.error(err.message || '操作失败')
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-tag {
  margin: 7px;
}

.row-top {
  border-top: 1px solid #eeeeee;
}

.row-bottom {
  border-bottom: 1px solid #eeeeee;
}
</style>